
import os
import xlrd
from Config import EXCEL_DIR
from Config import EXCEL_EXT
from Config import JSONDataDir
from ConfigDataGen import ConfigDataGen
from TSCodeGen import  TSCodeGen
from Config import TSCodeDir

class Excel2TS:


    # 构造函数
    def __init__(self):
        self.mExcelFiles = []  # 所有的excel文件

    # 外部处理函数
    def Process(self):
        print("========================================>")
        self.RecursiveSearchExcel(EXCEL_DIR)
        print("Excel 序列化完成！开始生成脚本文件")
        print("========================================>")
        self.ProcessExcelExportUnity()
        print("脚本文件生成完成！")

    # 递归查找文件
    def RecursiveSearchExcel(self, path):
        for pathdir in os.listdir(path):  # 遍历当前目录
            fullpath = os.path.join(path, pathdir)

            print("正在序列化： " + fullpath, "      后缀名 ： " +  os.path.splitext(fullpath)[1])
            if os.path.isdir(fullpath):
                self.RecursiveSearchExcel(fullpath)
            elif os.path.isfile(fullpath):
                if os.path.splitext(fullpath)[1] == EXCEL_EXT and os.path.splitext(os.path.basename(fullpath))[0].startswith("~") is False:
                    self.mExcelFiles.append(fullpath)

    # 处理excel文件
    def ProcessExcelExportUnity(self):

        TSCodePath = TSCodeDir + "generate/"
        if os.path.exists(TSCodePath) == True:
            os.system('del \"' + TSCodePath + '\"/F /Q')

        allbytesdata = "{"

        # 处理每个文件
        for filename in self.mExcelFiles:
            data = xlrd.open_workbook(filename)
            table = data.sheets()[0]
            fields = self.FilterFieldData(table)
            # 数据
            cfgbytes = ConfigDataGen.Process(table)
            clasaneme = os.path.basename(filename).split(".")[0]
            allbytesdata += "\n\"" + clasaneme + "\":" + cfgbytes + ","

            # 代码
            TSCodeGen.Process(filename, fields, table)

        allbytesdata = allbytesdata[:- 1]
        allbytesdata += "\n}"
        # 后处理
        ConfigDataGen.Save(allbytesdata, JSONDataDir)
        TSCodeGen.GenDictionaryCode()
        TSCodeGen.GenConfigMangerCode(self.mExcelFiles)
        print("序列化完成， 共" + str(len(self.mExcelFiles)) + "个文件")

    # 筛选字段数据
    def FilterFieldData(self, table):
        fields = []
        for index in range(table.ncols):
            fields.append(index)
                   

        return fields